package com.ruoyi.api;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.biz.domain.FrontUser;
import com.ruoyi.biz.mapper.FrontUserMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/login")
@Slf4j
public class LoginController {
    @Resource
    private FrontUserMapper frontUserMapper;

    /*前台用户登录*/
    @PostMapping
    public AjaxResult login(@RequestBody FrontUser frontUser){
        // 对账号和密码进行校验
        String account = frontUser.getAccount();
        String password = frontUser.getPassword();
        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(password)){
            throw new BaseException("账号或密码不能为空");
        }
        FrontUser selectUser = frontUserMapper.selectByAccountAndPassword(account, password);
        if(ObjectUtils.isEmpty(selectUser)){
            throw new BaseException("账号或密码错误");
        }

        // 登录
        StpUtil.login(selectUser.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        AjaxResult success = AjaxResult.success();
        success.put(tokenInfo.getTokenName(), tokenInfo.getTokenValue());

        return success;

    }

    /*获取登录用户信息*/
    @GetMapping("/info")
    public AjaxResult getLoginInfo(){
        // 获取登录用户id
        log.info("是否已登录,{}",StpUtil.isLogin());
        log.info("登录token,{}:{}",StpUtil.getTokenName(),StpUtil.getTokenValue());
        long loginId;
        try {
            loginId = StpUtil.getLoginIdAsLong();
        }catch (Exception e){
            throw new BaseException("用户未登录");
        }
        // 根据用户id查询用户信息
        FrontUser frontUser = frontUserMapper.selectFrontUserById(loginId);
        if(ObjectUtils.isEmpty(frontUser)){
            throw new BaseException("用户未登录");
        }
        return AjaxResult.success(frontUser);
    }

    /*
    * 退出登录
    * */
    @GetMapping("/logout")
    public AjaxResult logout(){
        StpUtil.logout();
        return AjaxResult.success("退出登录成功");
    }
}
